package com.mgvlife.ddlw.util;

import java.io.File;
import java.io.IOException;

import com.mgvlife.ddlw.entity.Clazz;
import com.mgvlife.ddlw.entity.Schedule;
import com.mgvlife.ddlw.entity.SignInInfo;
import com.mgvlife.ddlw.entity.Student;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class ExcelUtils {
	public static File writeExcel(String filePath, String fileName, String sheetName, Schedule schedule) {
		WritableWorkbook wwb = null;
		File excelFile = null;
		try {
			File file = new File(filePath);
			if (!file.exists()) {
				file.mkdir();
				System.out.println("文件夹已创建");
			}
			// 新建立一个jxl文件
			// 定义文件名格式并创建
			excelFile = File.createTempFile(fileName, ".xls", new File(filePath));
			// 首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象
			wwb = Workbook.createWorkbook(excelFile);
			if (wwb != null) {
				// 创建一个可写入的工作表
				// Workbook的createSheet方法有两个参数，第一个是工作表的名称，第二个是工作表在工作薄中的位置
				WritableSheet ws = wwb.createSheet(sheetName, 0);
				Label studentId = new Label(0, 0, "学号");
				ws.addCell(studentId);
				Label studentName = new Label(1, 0, "姓名");
				ws.addCell(studentName);
				Label status = new Label(2, 0, "签到状态");
				ws.addCell(status);
				Label clazz = new Label(3, 0, "班级名");
				ws.addCell(clazz);
				int i = 1;
				for (SignInInfo signInInfo : schedule.getSignInInfos()) {
					Student student = signInInfo.getStudent();
					Clazz clazz2 = student.getClazz();
					Label item0 = new Label(0, i, student.getStuId());
					ws.addCell(item0);
					Label item1 = new Label(1, i, student.getName());
					ws.addCell(item1);
					String status2 = "";
					switch (signInInfo.getSignInStatus()) {
						case -1:
							status2 = "未到";
							break;
						case 0:
							status2 = "迟到";
							break;
						case 1:
							status2 = "已到";
							break;
						case 2:
							status2 = "早退";
							break;
						case 3:
							status2 = "病假";
							break;
						case 4:
							status2 = "事假";
							break;
						default:
							status2 = "未到";
							break;
					}
					Label item2 = new Label(2, i, status2);
					ws.addCell(item2);
					Label item3 = new Label(3, i, clazz2.getGrade()+clazz2.getMajor()+clazz2.getClazzNum());
					ws.addCell(item3);
					i ++;
				}
				// 从内存中写入文件中
				wwb.write();
				// 关闭资源，释放内存
				wwb.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RowsExceededException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
		return excelFile;
	}
}
